<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Delete,
  Edit,
  Plus,
  Refresh,
  Search,
  Setting,
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import {
  getBuildingController,
  getHouseController,
  getPropertyFeeController,
  getPropertyTypeController,
} from '@/api-client'
import type {
  Building,
  HouseVO,
  PropertyFeeQueryRequest,
  PropertyFeeSaveRequest,
  PropertyFeeVO,
  PropertyType,
  PropertyTypeSaveRequest,
} from '@/api-client'

interface PropertyFeeFormModel {
  id?: number
  buildingId?: number
  houseId?: number
  typeId?: number
  money?: number
  status?: number
  remarks?: string
  dateRange: string[]
}

interface PropertyTypeFormModel {
  id?: number
  name: string
  price?: number
  unit?: string
  remarks?: string
}

const propertyFeeApi = getPropertyFeeController()
const propertyTypeApi = getPropertyTypeController()
const buildingApi = getBuildingController()
const houseApi = getHouseController()

const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<PropertyFeeVO[]>([])
const total = ref(0)
const selectedRows = ref<PropertyFeeVO[]>([])

const buildingOptions = ref<Building[]>([])
const searchHouseOptions = ref<HouseVO[]>([])
const formHouseOptions = ref<HouseVO[]>([])
const propertyTypeOptions = ref<PropertyType[]>([])

const pagination = reactive({
  current: 1,
  pageSize: 10,
})

const searchForm = reactive<PropertyFeeQueryRequest>({
  current: 1,
  pageSize: 10,
  typeId: undefined,
  houseId: undefined,
  ownerName: '',
  status: undefined,
  remarks: '',
})

const searchState = reactive({
  buildingId: undefined as number | undefined,
  startDateRange: [] as string[] | [],
  endDateRange: [] as string[] | [],
})

const createEmptyForm = (): PropertyFeeFormModel => ({
  id: undefined,
  buildingId: undefined,
  houseId: undefined,
  typeId: undefined,
  money: undefined,
  status: 0,
  remarks: '',
  dateRange: [],
})

const feeForm = reactive<PropertyFeeFormModel>(createEmptyForm())
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const isEdit = ref(false)

const rules = reactive<FormRules<PropertyFeeFormModel>>({
  typeId: [{ required: true, message: '请选择收费项目', trigger: 'change' }],
  buildingId: [{ required: true, message: '请选择所属楼栋', trigger: 'change' }],
  houseId: [{ required: true, message: '请选择关联房屋', trigger: 'change' }],
  money: [
    { required: true, message: '请输入收费金额', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value === undefined || value === null || Number.isNaN(Number(value))) {
          callback(new Error('请输入有效金额'))
          return
        }
        if (Number(value) < 0) {
          callback(new Error('金额不能小于0'))
          return
        }
        callback()
      },
      trigger: 'blur',
    },
  ],
})

const statusOptions = [
  { label: '未缴', value: 0, type: 'danger' },
  { label: '已缴', value: 1, type: 'success' },
  { label: '部分缴', value: 2, type: 'warning' },
]

const statusMap = computed(() =>
  new Map(statusOptions.map((item) => [item.value, { label: item.label, type: item.type }]))
)

const typeDialogVisible = ref(false)
const typeLoading = ref(false)
const typeFormRef = ref<FormInstance>()
const typeForm = reactive<PropertyTypeFormModel>({ name: '', price: undefined, unit: '', remarks: '' })
const typeRules = reactive<FormRules<PropertyTypeFormModel>>({
  name: [{ required: true, message: '请输入收费项目名称', trigger: 'blur' }],
})
const editingTypeId = ref<number | undefined>()

const houseCache = new Map<number, HouseVO[]>()

const formatDate = (value?: string) => {
  if (!value) return '-'
  return dayjs(value).format('YYYY-MM-DD HH:mm')
}

const fetchPropertyTypeList = async () => {
  try {
    const response = await propertyTypeApi.list1()
    if (response.code === 200) {
      propertyTypeOptions.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取收费项目失败')
    }
  } catch (error) {
    console.error('fetchPropertyTypeList error:', error)
    ElMessage.error('获取收费项目失败，请稍后重试')
  }
}

const fetchBuildingList = async () => {
  try {
    const response = await buildingApi.getAllBuildings()
    if (response.code === 200) {
      buildingOptions.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取楼栋信息失败')
    }
  } catch (error) {
    console.error('fetchBuildingList error:', error)
    ElMessage.error('获取楼栋信息失败，请稍后重试')
  }
}

const loadHousesByBuilding = async (buildingId: number) => {
  if (houseCache.has(buildingId)) {
    return [...(houseCache.get(buildingId) || [])]
  }
  try {
    const response = await houseApi.getHousesByBuildingId(buildingId)
    if (response.code === 200) {
      const list = response.data || []
      houseCache.set(buildingId, list)
      return [...list]
    }
    ElMessage.error(response.message || '获取房屋列表失败')
  } catch (error) {
    console.error('loadHousesByBuilding error:', error)
    ElMessage.error('获取房屋列表失败，请稍后重试')
  }
  return []
}

const applySearchRanges = () => {
  if (searchState.startDateRange.length === 2) {
    searchForm.startDateFrom = searchState.startDateRange[0]
    searchForm.startDateTo = searchState.startDateRange[1]
  } else {
    searchForm.startDateFrom = undefined
    searchForm.startDateTo = undefined
  }

  if (searchState.endDateRange.length === 2) {
    searchForm.endDateFrom = searchState.endDateRange[0]
    searchForm.endDateTo = searchState.endDateRange[1]
  } else {
    searchForm.endDateFrom = undefined
    searchForm.endDateTo = undefined
  }
}

const fetchPropertyFeeList = async () => {
  loading.value = true
  applySearchRanges()
  try {
    const response = await propertyFeeApi.search1({
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    })
    if (response.code === 200 && response.data) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取物业收费数据失败')
    }
  } catch (error) {
    console.error('fetchPropertyFeeList error:', error)
    ElMessage.error('获取物业收费数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const resetSearchForm = () => {
  searchForm.typeId = undefined
  searchForm.houseId = undefined
  searchForm.ownerName = ''
  searchForm.status = undefined
  searchForm.remarks = ''
  searchState.buildingId = undefined
  searchState.startDateRange = []
  searchState.endDateRange = []
  searchHouseOptions.value = []
  searchForm.startDateFrom = undefined
  searchForm.startDateTo = undefined
  searchForm.endDateFrom = undefined
  searchForm.endDateTo = undefined
}

const handleSearch = () => {
  pagination.current = 1
  searchForm.current = 1
  fetchPropertyFeeList()
}

const handleReset = () => {
  resetSearchForm()
  handleSearch()
}

const handleSelectionChange = (rows: PropertyFeeVO[]) => {
  selectedRows.value = rows
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchPropertyFeeList()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchPropertyFeeList()
}

const openDialog = () => {
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
  submitLoading.value = false
  formRef.value?.clearValidate()
}

const resetForm = () => {
  Object.assign(feeForm, createEmptyForm())
  formHouseOptions.value = []
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  openDialog()
}

const handleEdit = async (row: PropertyFeeVO) => {
  isEdit.value = true
  resetForm()
  feeForm.id = row.id
  feeForm.typeId = row.typeId
  feeForm.houseId = row.houseId
  feeForm.money = row.money
  feeForm.status = row.status ?? 0
  feeForm.remarks = row.remarks || ''
  feeForm.dateRange = []
  if (row.startDate && row.endDate) {
    feeForm.dateRange = [
      dayjs(row.startDate).format('YYYY-MM-DD HH:mm:ss'),
      dayjs(row.endDate).format('YYYY-MM-DD HH:mm:ss'),
    ]
  }
  const buildingId = row.house?.building?.id
  if (buildingId) {
    feeForm.buildingId = buildingId
    const houses = await loadHousesByBuilding(buildingId)
    formHouseOptions.value = houses
  }
  openDialog()
}

const submitForm = async (form: FormInstance | undefined) => {
  if (!form) return
  await form.validate(async (valid) => {
    if (!valid) return
    if (!feeForm.typeId || !feeForm.houseId || feeForm.money === undefined) return

    const payload: PropertyFeeSaveRequest = {
      typeId: feeForm.typeId,
      houseId: feeForm.houseId,
      money: Number(feeForm.money),
      status: feeForm.status,
      remarks: feeForm.remarks,
    }

    if (feeForm.dateRange.length === 2) {
      payload.startDate = feeForm.dateRange[0]
      payload.endDate = feeForm.dateRange[1]
    }

    submitLoading.value = true
    try {
      if (isEdit.value && feeForm.id) {
        await propertyFeeApi.update3(feeForm.id, payload)
        ElMessage.success('更新成功')
      } else {
        await propertyFeeApi.add3(payload)
        ElMessage.success('新增成功')
      }
      closeDialog()
      fetchPropertyFeeList()
    } catch (error) {
      console.error('submitForm error:', error)
      ElMessage.error(isEdit.value ? '更新失败，请稍后重试' : '新增失败，请稍后重试')
    } finally {
      submitLoading.value = false
    }
  })
}

const handleDelete = async (row: PropertyFeeVO) => {
  if (!row.id) return
  try {
    await ElMessageBox.confirm('确认删除该收费记录吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    loading.value = true
    await propertyFeeApi.delete3({ id: row.id })
    ElMessage.success('删除成功')
    fetchPropertyFeeList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleDelete error:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const handleBatchDelete = async () => {
  const ids = selectedRows.value
    .map((item) => item.id)
    .filter((id): id is number => id !== undefined)
  if (ids.length === 0) {
    ElMessage.warning('请先选择要删除的记录')
    return
  }
  try {
    await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 条记录吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    loading.value = true
    await propertyFeeApi.deleteBatch1(ids)
    ElMessage.success('批量删除成功')
    fetchPropertyFeeList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleBatchDelete error:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const openTypeDialog = () => {
  typeDialogVisible.value = true
  fetchPropertyTypeList()
  resetTypeForm()
}

const resetTypeForm = () => {
  editingTypeId.value = undefined
  Object.assign(typeForm, { name: '', price: undefined, unit: '', remarks: '' })
  typeFormRef.value?.clearValidate()
}

const handleEditType = (type: PropertyType) => {
  editingTypeId.value = type.id
  Object.assign(typeForm, {
    id: type.id,
    name: type.name || '',
    price: type.price,
    unit: type.unit || '',
    remarks: type.remarks || '',
  })
}

const submitTypeForm = async (form: FormInstance | undefined) => {
  if (!form) return
  await form.validate(async (valid) => {
    if (!valid) return
    const payload: PropertyTypeSaveRequest = {
      name: typeForm.name,
      price: typeForm.price,
      unit: typeForm.unit,
      remarks: typeForm.remarks,
    }
    typeLoading.value = true
    try {
      if (editingTypeId.value) {
        await propertyTypeApi.update2(editingTypeId.value, payload)
        ElMessage.success('更新收费项目成功')
      } else {
        await propertyTypeApi.add2(payload)
        ElMessage.success('新增收费项目成功')
      }
      await fetchPropertyTypeList()
      resetTypeForm()
    } catch (error) {
      console.error('submitTypeForm error:', error)
      ElMessage.error('保存失败，请稍后重试')
    } finally {
      typeLoading.value = false
    }
  })
}

const handleDeleteType = async (type: PropertyType) => {
  if (!type.id) return
  try {
    await ElMessageBox.confirm(`确认删除收费项目「${type.name}」吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    await propertyTypeApi.delete2({ id: type.id })
    ElMessage.success('删除成功')
    fetchPropertyTypeList()
    resetTypeForm()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('handleDeleteType error:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

const handleSearchBuildingChange = async (buildingId?: number) => {
  searchForm.houseId = undefined
  if (!buildingId) {
    searchHouseOptions.value = []
    return
  }
  const houses = await loadHousesByBuilding(buildingId)
  searchHouseOptions.value = houses
}

const handleFormBuildingChange = async (buildingId?: number) => {
  feeForm.houseId = undefined
  if (!buildingId) {
    formHouseOptions.value = []
    return
  }
  const houses = await loadHousesByBuilding(buildingId)
  formHouseOptions.value = houses
}

watch(
  () => searchState.buildingId,
  (value) => {
    handleSearchBuildingChange(value)
  }
)

watch(
  () => feeForm.buildingId,
  (value) => {
    handleFormBuildingChange(value)
  }
)

onMounted(async () => {
  await Promise.all([fetchBuildingList(), fetchPropertyTypeList()])
  fetchPropertyFeeList()
})
</script>

<template>
  <div class="property-charge-view">
    <div class="page-header">
      <div>
        <h2>物业收费管理</h2>
        <p>查看、登记与维护物业收费记录，支持按房屋和收费项目筛选。</p>
      </div>
      <el-button type="primary" :icon="Setting" @click="openTypeDialog"> 管理收费项目 </el-button>
    </div>

    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="所属楼栋">
          <el-select
            v-model="searchState.buildingId"
            placeholder="请选择楼栋"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="item in buildingOptions"
              :key="item.id"
              :label="`${item.numbers || ''}${item.units ? ` ${item.units}` : ''}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋">
          <el-select
            v-model="searchForm.houseId"
            placeholder="请选择房屋"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="item in searchHouseOptions"
              :key="item.id"
              :label="`${item.building?.numbers || ''} ${item.numbers || ''}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收费项目">
          <el-select
            v-model="searchForm.typeId"
            placeholder="请选择收费项目"
            clearable
            filterable
            style="width: 180px"
          >
            <el-option
              v-for="item in propertyTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 150px">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业主姓名">
          <el-input
            v-model="searchForm.ownerName"
            placeholder="请输入业主姓名"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="searchState.startDateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始"
            end-placeholder="结束"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 320px"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchState.endDateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始"
            end-placeholder="结束"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 320px"
          />
        </el-form-item>
        <el-form-item label="备注关键词">
          <el-input
            v-model="searchForm.remarks"
            placeholder="请输入备注关键词"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"> 搜索 </el-button>
          <el-button :icon="Refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-section">
      <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增收费记录 </el-button>
      <el-button
        type="danger"
        :icon="Delete"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="收费项目" min-width="160">
          <template #default="{ row }">
            <div class="cell-strong">{{ row.typeName || '-' }}</div>
            <div class="cell-sub" v-if="row.typeUnit || row.typePrice">
              {{ row.typePrice ? `￥${row.typePrice}` : '' }}
              <span v-if="row.typeUnit">/{{ row.typeUnit }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="房屋" min-width="160">
          <template #default="{ row }">
            <div class="cell-strong">
              {{ row.house?.building?.numbers || '-' }} {{ row.house?.numbers || '' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="业主" min-width="140">
          <template #default="{ row }">
            <div>{{ row.owner?.name || '-' }}</div>
            <div class="cell-sub" v-if="row.owner?.tel">{{ row.owner.tel }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="金额 (元)" width="120">
          <template #default="{ row }">
            ￥{{ row.money?.toFixed(2) ?? '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="收费周期" min-width="200">
          <template #default="{ row }">
            <div>{{ formatDate(row.startDate) }}</div>
            <div class="cell-sub">至 {{ formatDate(row.endDate) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="statusMap.get(row.status || 0)?.type">
              {{ statusMap.get(row.status || 0)?.label || '未缴' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{ row }">
            <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑收费记录' : '新增收费记录'"
      width="560px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="feeForm" :rules="rules" label-width="100px">
        <el-form-item label="收费项目" prop="typeId">
          <el-select v-model="feeForm.typeId" placeholder="请选择收费项目" filterable>
            <el-option
              v-for="item in propertyTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属楼栋" prop="buildingId">
          <el-select v-model="feeForm.buildingId" placeholder="请选择楼栋" filterable>
            <el-option
              v-for="item in buildingOptions"
              :key="item.id"
              :label="`${item.numbers || ''}${item.units ? ` ${item.units}` : ''}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋" prop="houseId">
          <el-select v-model="feeForm.houseId" placeholder="请选择房屋" filterable>
            <el-option
              v-for="item in formHouseOptions"
              :key="item.id"
              :label="`${item.building?.numbers || ''} ${item.numbers || ''}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收费金额" prop="money">
          <el-input v-model.number="feeForm.money" type="number" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="收费周期">
          <el-date-picker
            v-model="feeForm.dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="缴费状态">
          <el-radio-group v-model="feeForm.status">
            <el-radio :label="item.value" v-for="item in statusOptions" :key="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="feeForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm(formRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="typeDialogVisible"
      title="收费项目管理"
      width="720px"
      :close-on-click-modal="false"
    >
      <div class="type-dialog">
        <div class="type-form">
          <el-form ref="typeFormRef" :model="typeForm" :rules="typeRules" label-width="90px">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="typeForm.name" placeholder="请输入项目名称" maxlength="50" />
            </el-form-item>
            <el-form-item label="计费单价">
              <el-input v-model.number="typeForm.price" type="number" placeholder="请输入金额" />
            </el-form-item>
            <el-form-item label="计费单位">
              <el-input v-model="typeForm.unit" placeholder="例如：元/平方米" maxlength="25" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="typeForm.remarks"
                type="textarea"
                :rows="2"
                placeholder="可填写说明"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="resetTypeForm">重置</el-button>
              <el-button type="primary" :loading="typeLoading" @click="submitTypeForm(typeFormRef)">
                {{ editingTypeId ? '保存修改' : '新增项目' }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="type-table">
          <el-table :data="propertyTypeOptions" border stripe height="360">
            <el-table-column prop="name" label="项目名称" min-width="160" />
            <el-table-column label="单价" min-width="120">
              <template #default="{ row }">
                <span v-if="row.price">￥{{ row.price }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" min-width="120" />
            <el-table-column prop="remarks" label="备注" min-width="180" show-overflow-tooltip />
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" :icon="Edit" @click="handleEditType(row)">
                  编辑
                </el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="handleDeleteType(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="css" scoped>
.property-charge-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.page-header h2 {
  margin: 0 0 6px;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.search-section,
.action-section,
.table-section,
.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.search-section {
  margin-bottom: 16px;
}

.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
  margin: 16px 0;
}

.table-section {
  margin-bottom: 16px;
}

.pagination-section {
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.cell-strong {
  font-weight: 500;
  color: #303133;
}

.cell-sub {
  color: #909399;
  font-size: 12px;
}

.type-dialog {
  display: grid;
  grid-template-columns: 320px 1fr;
  gap: 16px;
}

.type-form {
  background: #f9fafc;
  padding: 16px;
  border-radius: 8px;
}

.type-table {
  border-radius: 8px;
  overflow: hidden;
}

@media (max-width: 960px) {
  .type-dialog {
    grid-template-columns: 1fr;
  }
}
</style>
